package start.demo01.email;

import javax.mail.*;
import javax.mail.search.*;
import java.util.Date;
import java.util.Properties;

public class MailReceives {

//    private static String pop3Server = "pop.qq.com";
//    private static String protocol = "pop3";
    private static String pop3Server = "imap.qq.com";//993
    private static String protocol = "imap";
    private static String username = "790867216@qq.com";
    private static String password = "khmkygxoiexvbfgf"; //

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol);
        props.setProperty("mail.smtp.host", pop3Server);
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);
        Store store = session.getStore(protocol);
        store.connect(pop3Server, username, password);
        System.out.println("连接服务器");
        start(store);
        store.close();
    }

    private static void start(Store store) throws Exception {
        Folder folder = store.getFolder("INBOX");//
        folder.open(Folder.READ_WRITE); //
        long millis = System.currentTimeMillis();
        Message[] messages = searchMails(folder, millis - 1000 * 60*60*24, millis);//
        for (Message message : messages) {
            String subject = message.getSubject();//
            Address from = message.getFrom()[0];//
            System.out.println(" " + subject + "\t " + from);
            message.writeTo(System.out);//
        }
        folder.close(false);
    }

    /**
     * @param folder
     * @throws Exception
     */
    private static Message[] searchMails(Folder folder, long start, long end) throws Exception {
        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false true
        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, new Date(start));
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, new Date(end));
//        FromStringTerm fromStringTerm = new FromStringTerm("???");
        SearchTerm andTerm = new AndTerm(new SearchTerm[]{comparisonTermGe,
                comparisonTermLe, ft});
        Message[] messages = folder.search(andTerm); // message
        return messages;
    }
}
